import { message } from '@/components/XtxUI'
import type { CheckoutInfo, OrderDetail, OrderInfo } from '@/types'
import { http } from '@/utils/request'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useCartStore } from '..'
import router from '@/router'

export const useCheckoutStore = defineStore('checkout', () => {
  const checkoutInfo = ref<CheckoutInfo>()
  const orderDetail = ref<OrderDetail>()

  // 获取结算信息，生成预付单
  const getCheckoutInfo = async () => {
    const res = await http<CheckoutInfo>('GET', '/member/order/pre')
    checkoutInfo.value = res.data.result
  }

  // 提交订单
  const submitCheckout = async (data: object) => {
    const res = await http<OrderInfo>('POST', '/member/order', data)
    message({ type: 'success', text: '下单成功' })
    // 注意要使用replace()跳转支付页面，不要用push()
    router.replace(`/member/pay/${res.data.result.id}`)
    // 更新购物车，清除已下单的商品
    const cartStore = useCartStore()
    cartStore.getCartList()
  }

  // 获取订单详情
  const getOrderDetail = async (orderId: string) => {
    const res = await http<OrderDetail>('get', `/member/order/${orderId}`)
    const { countdown } = res.data.result
    // 如果后端返回秒数-1，表示订单超时，不展示支付详情页
    if (countdown === -1) {
      router.replace('/cart')
      return message({ type: 'warn', text: '订单已超时，请重新下单' })
    }
    orderDetail.value = res.data.result
  }

  return { checkoutInfo, orderDetail, getCheckoutInfo, submitCheckout, getOrderDetail }
})
